package com.cumt.threeway.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.cumt.threeway.R;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.model.User;
import com.cumt.threeway.table.UserEntity;
import com.cumt.threeway.util.ThreeWayData;
import com.cumt.threeway.util.ThreeWayUtil;
import com.cumt.threeway.view.dialog.CheckCodeDialog;
import com.cumt.threeway.view.dialog.ForgetPwdDialog;
import com.cumt.threeway.view.dialog.ResetPswFinishDialog;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;


/**
 * Created by Jingjing.Hu on 2016/4/14.
 */
public class LoginActivity extends FragmentActivity implements View.OnClickListener, View.OnFocusChangeListener,PlatformActionListener {

    private final int LOGIN_ACCOUNT = 1;
    private final int LOGIN_PASSWORD = 2;
    private final int LOGIN_ENABLED = 3;
    private final int MSG_AUTH_SUCCESS = 4;
    private final int MSG_AUTH_CANCEL = 5;
    private final int MSG_AUTH_ERROR = 6;

    private EditText mAccountEditText;
    private EditText mPasswordEditText;
    private Button mDelAccountView;
    private Button mDelPasswordView;
    private View mLoginQqView;
    private View mLoginWeiboView;
    private TextView mForgetPwdView;
    private Button mBtnLogin;
    private View mRegisterView;
    private int mLoginCount = 0;
    private RequestQueue queue;
    private int mKey;
    private String mNeedLoginKey;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_AUTH_SUCCESS:
//                    ThreeWayUtil.getInstance().showToast(LoginActivity.this, "正在登录...");
                    break;
                case MSG_AUTH_CANCEL:
                    Toast.makeText(LoginActivity.this,"授权取消",Toast.LENGTH_LONG).show();
                    break;
                case MSG_AUTH_ERROR:
                    Toast.makeText(LoginActivity.this,"授权失败",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
        initView();
    }

    private void initView() {
        queue = Volley.newRequestQueue(this);
        Intent i = getIntent();
        mKey = i.getIntExtra("key",0);
        mNeedLoginKey = i.getStringExtra("needLogin");
        findViewById(R.id.btn_login_back).setOnClickListener(this);
        mAccountEditText = (EditText) findViewById(R.id.et_login_phonenumber);
        mPasswordEditText = (EditText) findViewById(R.id.et_login_password);
        mDelAccountView = (Button) findViewById(R.id.btn_login_del1);
        mDelPasswordView = (Button) findViewById(R.id.btn_login_del2);
        mForgetPwdView = (TextView) findViewById(R.id.tv_login_forget_password);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mRegisterView = findViewById(R.id.tv_login_register_account);
        mLoginQqView = findViewById(R.id.iv_qq_login);
        mLoginWeiboView = findViewById(R.id.iv_weibo_login);
        mForgetPwdView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mForgetPwdView.getPaint().setAntiAlias(true);// 抗锯齿

        mAccountEditText.addTextChangedListener(new LoginTextChangeListener(LOGIN_ACCOUNT));
        mPasswordEditText.addTextChangedListener(new LoginTextChangeListener(LOGIN_PASSWORD));
        mAccountEditText.setOnFocusChangeListener(this);
        mPasswordEditText.setOnFocusChangeListener(this);

        mDelAccountView.setOnClickListener(this);
        mDelPasswordView.setOnClickListener(this);
        mForgetPwdView.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        mRegisterView.setOnClickListener(this);
        mLoginQqView.setOnClickListener(this);
        mLoginWeiboView.setOnClickListener(this);

        mBtnLogin.setClickable(false);
        mBtnLogin.setAlpha(0.4f);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        saveUserInfro(platform);
        if (i == Platform.ACTION_USER_INFOR) {
            Message msg = new Message();
            msg.what = MSG_AUTH_SUCCESS;
            msg.obj = new Object[] {platform.getName(), hashMap};
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if (i == Platform.ACTION_USER_INFOR) {
            mHandler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int i) {
        if (i == Platform.ACTION_USER_INFOR) {
            mHandler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }


    private void saveUserInfro(Platform platform) {
        User user = new User();
        String userID = platform.getDb().getUserId();
        String userName  = platform.getDb().getUserName();
        String userGender = platform.getDb().getUserGender();
        String url = platform.getDb().getUserIcon();
        String account = platform.getDb().getPlatformNname();
        user.setUserID(8149);//因为此处第三方登录的userID带有字母，所以用Integer.ParseInt转会报错，因为没有服务，所以暂时写了一个ID作为测试，性别写1的原因同上
        user.setName(userName);
        user.setImagePath(url);
        user.setGender(1);
        user.setAccount(account);
        ThreeWayUtil.getInstance().saveLoginAccount(this, platform.getDb().getPlatformNname());
        ThreeWayUtil.getInstance().saveUserName(this, userName);
        Intent intent = new Intent();
        intent.putExtra("user", user);
        setResult(RESULT_OK, intent);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                ThreeWayUtil.getInstance().showToast(LoginActivity.this, "正在登录...", 400);
                finish();
            }
        }, 1000);
    }

    class LoginTextChangeListener implements TextWatcher {

        private int mType = 0;

        public LoginTextChangeListener(int type) {
            mType = type;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            switch (mType) {
                case LOGIN_ACCOUNT:
                    if (!TextUtils.isEmpty(s)) {
                        mDelAccountView.setVisibility(View.VISIBLE);
                        mLoginCount |= LOGIN_ACCOUNT;
                    } else {
                        mDelAccountView.setVisibility(View.GONE);
                        if ((mLoginCount & LOGIN_ACCOUNT) == 1) {
                            mLoginCount -= LOGIN_ACCOUNT;
                        }
                    }
                    break;
                case LOGIN_PASSWORD:
                    if (!TextUtils.isEmpty(s)) {
                        mDelPasswordView.setVisibility(View.VISIBLE);
                        mLoginCount |= LOGIN_PASSWORD;
                    } else {
                        mDelPasswordView.setVisibility(View.GONE);
                        if ((mLoginCount & LOGIN_PASSWORD) == LOGIN_PASSWORD) {
                            mLoginCount -= LOGIN_PASSWORD;
                        }
                    }
                    break;
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(mLoginCount == LOGIN_ENABLED) {
                mBtnLogin.setClickable(true);
                mBtnLogin.setAlpha(0.8f);
            } else {
                mBtnLogin.setClickable(false);
                mBtnLogin.setAlpha(0.4f);
            }
        }
    }

    public void goCheckCodeDialog(String phoneNum) {
        CheckCodeDialog checkCodeDialog = CheckCodeDialog.newInstance(phoneNum, null, null);
        checkCodeDialog.show(getSupportFragmentManager(), "checkCodeDialog");
    }

    public void goResetPwdFinishDialog(String phoneNum) {
        ResetPswFinishDialog resetPswFinishDialog = ResetPswFinishDialog.newInstance(phoneNum);
        resetPswFinishDialog.show(getFragmentManager(), "resetPswFinishDialog");
    }

    private void goRegisterActivity() {
        finish();
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.btn_login_back:
                Intent intent = new Intent();
                User user = new User();
                intent.putExtra("user", user);
                setResult(-3, intent);
                finish();
                break;
            case R.id.btn_login_del1:
                setDelViewGone(mAccountEditText, mDelAccountView);
                break;
            case R.id.btn_login_del2:
                setDelViewGone(mPasswordEditText, mDelPasswordView);
                break;
            case R.id.btn_login:
                if(ThreeWayUtil.getInstance().isPhoneNum(getEditContent(mAccountEditText))) {
                    ThreeWayUtil.getInstance().showToast(this, getResources().getString(R.string.tip_phone_error));
                    getEditFocus(mAccountEditText);
                }else if (getEditContent(mPasswordEditText).length() < 6 || getEditContent(mPasswordEditText).length() > 16) {
                    ThreeWayUtil.getInstance().showToast(this, getResources().getString(R.string.tip_password_error));
                    getEditFocus(mPasswordEditText);
                } else {
                    checkAccountAndPassword();
                }
                break;
            case R.id.tv_login_register_account:
                goRegisterActivity();
                break;
            case R.id.tv_login_forget_password:
                ForgetPwdDialog forgetPwdDialog = ForgetPwdDialog.newInstance();
                forgetPwdDialog.show(getSupportFragmentManager(), "forgetPwdDialog");
                break;
            case R.id.iv_qq_login:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);
                break;
            case R.id.iv_weibo_login:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sina);
                break;
        }

    }

    //执行授权,获取用户信息
    private void authorize(Platform plat) {
        if (plat == null) {
            return;
        }
        plat.setPlatformActionListener(this);
        //关闭SSO授权
        plat.SSOSetting(true);
        plat.showUser(null);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.et_login_phonenumber:
                setDelViewStatus(hasFocus, getEditContent(mAccountEditText), mDelAccountView);
                ThreeWayUtil.getInstance().saveLoginAccount(this, getEditContent(mAccountEditText));
                break;
            case R.id.et_login_password:
                setDelViewStatus(hasFocus, getEditContent(mPasswordEditText), mDelPasswordView);
                break;
        }
    }

    public void setDelViewGone(EditText editText, View view) {
        editText.setText("");
        view.setVisibility(View.GONE);
    }

    private void setDelViewStatus(boolean hasFocus, String string, Button delButton) {
        if(hasFocus) {
//            parentView.setBackgroundResource(R.drawable.edit_text_pressed);
            if(!TextUtils.isEmpty(string)) {
                delButton.setVisibility(View.VISIBLE);
            }
        } else {
//            parentView.setBackgroundResource(R.drawable.edit_text_normal);
            if(!TextUtils.isEmpty(string)){
                delButton.setVisibility(View.GONE);
            }
        }
    }

    private String getEditContent(EditText editText) {
        return editText.getText().toString();
    }

    private void getEditFocus(EditText editText) {
        editText.requestFocus();
    }

    private void checkAccountAndPassword() {
        final String account = getEditContent(mAccountEditText);
        final String password = getEditContent(mPasswordEditText);
        UserEntity userEntity = ThreeWayData.getInstance().getUserInfoByName(account);
        if(TextUtils.isEmpty(userEntity.getAccount())) {
            ThreeWayUtil.getInstance().showToast(LoginActivity.this, getResources().getString(R.string.login_error));
            return;
        }
        if(!account.equals(userEntity.getAccount()) || !password.equals(userEntity.getPassword())) {
            ThreeWayUtil.getInstance().showToast(LoginActivity.this, getResources().getString(R.string.password_error));
        } else {
            ThreeWayUtil.getInstance().saveLoginAccount(LoginActivity.this, getEditContent(mAccountEditText));
            ThreeWayData.getInstance().addUserInfo(account, password, false);
            UserEntity userEntity1 = ThreeWayData.getInstance().getUserInfoByName(account);
            String userName;
            if (TextUtils.isEmpty(userEntity1.getUserName())) {
                userName = "母校徐海";
                ThreeWayData.getInstance().updateUserName(userName);
            } else {
                userName = userEntity1.getUserName();
            }
            final User user = new User();
            user.setAccount(account);
            user.setName(userName);
            ThreeWayUtil.getInstance().saveUserName(LoginActivity.this, userName);
            ThreeWayUtil.getInstance().showToast(LoginActivity.this, getResources().getString(R.string.login_success));
            if (mKey == ThreeWayConstant.INTENT_KEY_TO_LOGIN_1) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            } else if (ThreeWayConstant.REQUEST_CODE_FOR_LOGIN == mKey) {
                goMainManageActivity();
            } else if ("checkSubmitInfo".equals(mNeedLoginKey)) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(LoginActivity.this, CheckSubmitActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }, 1000);
            } else if ("submitFavourite".equals(mNeedLoginKey)) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setResult(-2);
                        finish();
                    }
                }, 1000);
            } else if ("writeStrategy".equals(mNeedLoginKey)) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setResult(RESULT_OK);
                        finish();
                    }
                }, 1000);
            } else {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.putExtra("user", user);
                        setResult(-2, intent);
                        finish();
                    }
                }, 1000);
            }
        }
//        if(!TextUtils.isEmpty(account) && !TextUtils.isEmpty(password)) {
//            StringRequest srPost = new StringRequest(Method.POST, URLS.IP + "NetServlet/LoginData",
//                    new Response.Listener<String>() {
//                        @Override
//                        public void onResponse(String response) {
//                            String loginResult = response.toString();
//                            if(TextUtils.isEmpty(loginResult)){
//                                ThreeWayUtil.getInstance().showToast(LoginActivity.this, getResources().getString(R.string.login_error));
//                            }
//                            try {
//                                JSONObject jsonObject = new JSONObject(loginResult);
//                                String flag = jsonObject.getString("loginResult");
//                                String userName = jsonObject.getString("userName");
//                                String iconPath = jsonObject.getString("iconPath");
//                                if(("true").equals(flag)) {
//                                    ThreeWayUtil.getInstance().saveLoginAccount(LoginActivity.this, getEditContent(mAccountEditText));
//                                    ThreeWayUtil.getInstance().saveUserName(LoginActivity.this, userName);
//                                    ThreeWayUtil.getInstance().showToast(LoginActivity.this, getResources().getString(R.string.login_success));
//                                    final User user = new User();
//                                    user.setAccount(account);
//                                    user.setName(userName);
//                                    user.setImagePath(iconPath);
//                        }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//
//                        }
//                    }, new Response.ErrorListener() {
//                @Override
//                public void onErrorResponse(VolleyError error) {
//                    Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
//                }
//            }) {
//                // 当手机发送请求时，回调用getParams方法，拼请求
//                @Override
//                protected Map<String, String> getParams() throws AuthFailureError {
//                    Map<String, String> map = new HashMap<String, String>();
//                    map.put("xingming", account);
//                    map.put("mima", password);
//                    return map;
//                }
//            };
//            queue.add(srPost);
//        }
    }

    private void goMainManageActivity() {
        Intent intent = new Intent(LoginActivity.this, MainManageActivity.class);
        intent.putExtra("key", ThreeWayConstant.REQUEST_CODE_FOR_LOGIN);
        startActivity(intent);
    }
}
